package net.cruciblesoftware.ghostspacekillah;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


class SceneView extends SurfaceView implements SurfaceHolder.Callback {

    public static int width, height;
    public static float lastTouchX, lastTouchY;

    private KillahThread thread;

    /* View constructor */
    public SceneView(Context context, AttributeSet attribs) {
        super(context, attribs);
        logi("creating SceneView...");
        SurfaceHolder holder = this.getHolder();
        holder.addCallback(this);

        // create thread here, start in surfaceCreated()
        thread = new KillahThread(holder);
    }


    public KillahThread getThread() {
        return thread;
    }


    @Override
    public boolean onTouchEvent(MotionEvent e) {
        lastTouchX = e.getRawX();
        lastTouchY = e.getRawY();
        return true;
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        width = this.getWidth();
        height = this.getHeight();
        thread.initField();
        thread.setRunning(true);
        thread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        width = w;
        height = h;
        logi("surface change: " + width + "x" + height);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        logi("surface holder is being destroyed");
        thread.setRunning(false);
        boolean retry = true;
        // loop until thread terminates
        while(retry) {
            try {
                thread.join();
                retry = false;
            }
            catch(InterruptedException e) { }
        }
    }


    /* Logging functions */
    private void logi(String msg) {
        android.util.Log.i(this.getClass().getName(), msg);
    }
    private void logw(String msg) {
        android.util.Log.w(this.getClass().getName(), msg);
    }
    private void loge(String msg) {
        android.util.Log.e(this.getClass().getName(), msg);
    }
}
